package com.liangchao.androidmediacodectest;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private HandlerThread handlerThread;
    private Handler childHandler,uiHandler;

    private EncodeUtil encodeUtil;
    private final static int MSG_START_ENCODE = 1;
    private MyEncodeProListener myEncodeProListener;
    public Button btEncode;
    public TextView tvEncode;



    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btEncode = findViewById(R.id.BtStartEncode);
        tvEncode = findViewById(R.id.encodepro);

        handlerThread = new HandlerThread("EncodeUtilThread");
        handlerThread.start();

        childHandler = new Handler(handlerThread.getLooper(), new ChildHandlerCallback());
        uiHandler = new Handler();

        btEncode.setOnClickListener(new BtEncodeClickListener());
        myEncodeProListener =new MyEncodeProListener();
    }

    class BtEncodeClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            childHandler.sendEmptyMessage(MSG_START_ENCODE);
        }
    }

    class MyEncodeProListener implements EncodeUtil.EncodeProgressListener{

        @Override
        public void onEncodeProgress(int progress) {
            uiHandler.post(new Runnable() {
                @Override
                public void run() {
                    tvEncode.setText("Encode Progress "+progress);
                }
            });

        }
    }

    class ChildHandlerCallback implements Handler.Callback {

        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == MSG_START_ENCODE) {
                encodeUtil = new EncodeUtil(getApplicationContext());
                encodeUtil.setEncodeProgressListener(myEncodeProListener);
                encodeUtil.setMimeType("video/avc");
                encodeUtil.setINPUT_WIDTH(1280);
                encodeUtil.setINPUT_HEIGHT(720);
                encodeUtil.initEncoder();
                new Thread(encodeUtil).start();
                encodeUtil.setInputSource(R.raw.r_1280_720);

                return true;
            } else
                return false;
        }
    }
}